import smtplib
import os
import sys
import json
from model import *


class mailService():
    '''
    Send email notifications
    '''
    def __init__(self):
        '''
        Load Config values
        '''
        self.cfg = {}
        self.addr = []
        self.thisMsg = None
        
        
        
    def loadConfig(self):
        '''
        Load Configuration Values
        File maintained outside of code base for security...
        ''' 
        configFile = 'email.cfg'
        file = os.getcwd() + '/'+ configFile
        try:
            fh = open(file)
            self.cfg = json.load(fh)
            fh.close()
        except:
            print "Can not read config data"
        
        
    
    def setAddr(self, eAddr):
        '''
        set list of email recipients 
        '''
        self.addr.append(eAddr)
         
        
    def setMsg(self, toAddr, fromAddr, eName, mid, msgType='invite' ):
        '''
        Notification service message
        '''
        Msg = {}
        
        
        Msg['invite'] = """To:%(To)s
From:%(From)s
Subject: Event Invite ( %(Event)s )\n\n

You have been invited to attend a new meeting.
Please click on the link below to respond to this invite. 

%(Link)s%(EventID)s
        
""" % {'Link': self.cfg['respUrl'], 'To': toAddr, 'From': fromAddr, 'Event': eName, 'EventID': mid  }
        

        Msg['cancel'] = """To:%(To)s
From:%(From)s
Subject: Event ( %(Event)s ) is canceled\n\n

This message is to let you know that the event has been canceled.
Your calendar has been updated to reflect this change.  

        
""" % { 'To': toAddr, 'From': fromAddr, 'Event': eName}

        Msg['resched'] = """To:%(To)s
From:%(From)s
Subject: Event ( %(Event)s ) has been rescheduled\n\n

To acknowledge these changes please click the link below. 

%(Link)s%(EventID)s
        
""" % {'Link': self.cfg['respUrl'], 'To': toAddr, 'From': fromAddr, 'Event': eName, 'EventID': mid}

        
        return Msg[msgType]
        
        
        
        
        

    def sendMsg(self, eName, mid, type='invite'):
        '''
        Send message(s)
        '''
        #msg= "Subject: Test Message\n\nThis is a test Message"
        
        
        #msg = self.setMsg()
        try: 
            addrs = ", ".join(self.addr)
        except:
            addrs = self.addr
        print "message type = %s" %(type)
        self.thisMsg = self.setMsg(addrs, self.cfg['account'], eName, mid, type)
        
        self.deliverMail()
        
        '''
        
        server = smtplib.SMTP(self.cfg['smtp_server'],self.cfg['smtp_port']) 
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(self.cfg['account'],self.cfg['pass'])
        server.sendmail(self.cfg['account'],self.addr, msg)
        server.close()
        '''
    def sendMail(self, subject):
        '''
        Custom mail interface
        '''
        msg= "Subject: Test Message\n\n%(Subject)s" % {'Subject': subject}
        server = smtplib.SMTP(self.cfg['smtp_server'],self.cfg['smtp_port']) 
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(self.cfg['account'],self.cfg['pass'])
        server.sendmail(self.cfg['account'],self.addr, msg)
        server.close()


    

    def deliverMail(self):
        '''
        deliver the mail...
        '''
        print "This is addr list => %s " %(self.addr)
        try:
            '''
            Attempt to send email
            Log failures
            '''
            server = smtplib.SMTP(self.cfg['smtp_server'],self.cfg['smtp_port']) 
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login(self.cfg['account'],self.cfg['pass'])
            server.sendmail(self.cfg['account'],self.addr, self.thisMsg)
            server.close()
        except:
            '''
            
            '''
            print "[Email] Failed to send email. Please check configuration file."
            

